/**
 * base64转换为文件
 * @param {*} dataurl
 * @param {*} filename
 * @returns
 */
function dataURLtoFile(dataurl: string, filename: string) {
    let arr: any = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    return new File([u8arr], filename, { type: mime })
}
/**
 * base64转二进制文件再传file文件
 * @param {*} dataurl
 * @param {*} fileName
 * @returns
 */
function dataURLtoBlobtoFile(dataurl: string, fileName: string) {
    let arr: any = dataurl.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
    }
    const theBlob: { [key: string]: any } = new Blob([u8arr], { type: mime })
    theBlob.lastModifiedDate = new Date()
    theBlob.name = fileName
    return theBlob
}
/**
 * 根据图片链接获取像素点组成的一维点阵数据, 结构为[R,G,B,A,R,G,B,A,...]
 * @param {*} data 图片链接
 */
function getImageData(data: string) {
    return new Promise((resolve) => {
        const img = new Image()
        img.setAttribute('crossOrigin', 'anonymous')
        img.src = data
        img.onload = function () {
            const canvas = document.createElement('canvas')
            const context = canvas.getContext('2d') as CanvasRenderingContext2D
            canvas.width = img.width
            canvas.height = img.height
            context.clearRect(0, 0, img.width, img.height)
            context.drawImage(img, 0, 0)
            const imageData = context.getImageData(0, 0, img.width, img.height)
            const base64 = canvas.toDataURL('image/png', 1)
            resolve({
                imageData,
                base64,
            })
        }
    })
}
/**
 * 读取file文件
 * @param file
 * @returns
 */
export function fileReader(file: File) {
    return new Promise(async (resolve) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function () {
            resolve(reader.result)
        }
    })
}
/**
 * 点阵rgb数据转base64格式
 * @param {*} info uint8ClampedArray
 */
type ImageData = {
    width: number
    height: number
    colorSpace: string
    data: Uint8ClampedArray
}
function uint8ToBase64(data: ImageData) {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
    canvas.width = data.width
    canvas.height = data.height
    ctx.putImageData(data, 0, 0)
    const base64 = canvas.toDataURL('image/png', 1)
    return base64
}
